//
// Created by wangxiyue on 2019/8/14.
//

#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>
#include <inaddr.h>
#include <ws2tcpip.h>

int main(int argc, char **argv)
{
    int                 listenfd, connfd;
    socklen_t           clilen;
    struct sockaddr_in  cliaddr, servaddr;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(12345);

    /* bind 到本地地址，端口为 12345 */
    bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
    /* listen 的 backlog 为 1024 */
    listen(listenfd, 1024);

    /* 循环处理用户请求 */
    for ( ; ; ) {
        clilen = sizeof(cliaddr);
        connfd = accept(listenfd, (SA *) &cliaddr, &clilen);
        read_data(connfd);   /* 读取数据 */
        close(connfd);          /* 关闭连接套接字，注意不是监听套接字 */
    }
}

void read_data(int sockfd)
{
    ssize_t  n;
    char buf[1024];

    int time = 0;
    for ( ; ; ) {
        fprintf(stdout, "block in read\n");
        if ( (n = Readn(sockfd, buf, 1024)) == 0)
            return;     /* connection closed by other end */

        time ++;
        fprintf(stdout, "1K read for %d \n", time);
        usleep(1000);
    }
}
